package com.ztjava.develop.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.client.PortalClient;
import com.ztjava.core.utiliy.StringUtil;
import com.ztjava.develop.model.autocode.AutocodeComponent;
import com.ztjava.develop.model.autocode.AutocodeModel;
import com.ztjava.develop.model.autocode.AutocodePlugin;
import com.ztjava.develop.service.AutocodeService;
import com.ztjava.ext.auth.annotation.UserController;
import com.ztjava.ext.auth.annotation.UserMethod;
import com.ztjava.ext.auth.bean.AuthSession;

@ControllerClass(path="/develop/autocode",client=PortalClient.class)
@UserController(portal=Constant.P_PORTAL)
public class AutocodePortalController extends BaseController{
	private static AutocodeService autocodeService = new AutocodeService();

	@UserMethod("DevelopAutocode")
	public void loadTable(){
		Integer plugin_id = getParaToInt("plugin_id");
		AutocodePlugin autocodePlugin = AutocodePlugin.dao.findById(plugin_id);
		String tablename  = getPara("tablename","");
		if(tablename.equals("")){
			renderError("表不能为空！");
			return;
		}
		try{
			List<Record> columnList = Db.find("select COLUMN_NAME as columnColumn,DATA_TYPE from information_schema.COLUMNS where TABLE_SCHEMA='"
			+autocodePlugin.getStr("db")+"' and TABLE_NAME='"+tablename+"' AND COLUMN_NAME not in ('id','create_time','update_time','create_user','update_user','enable_flag','sort') ORDER BY ORDINAL_POSITION DESC ");
			if(columnList.size()==0){
				renderError("没有字段！");
				return;
			}
			for(int i=0;i<columnList.size();i++){
				switch (columnList.get(i).getStr("DATA_TYPE")) {
				case "int":
					columnList.get(i).set("inputType", "digits");
					break;
				case "decimal":
					columnList.get(i).set("inputType", "number");
					break;
				default:
					break;
				}
			}
			setAttr(Constant.RESULT, Constant.SUCCESS);
			setAttr(Constant.MESSAGE, "操作成功！");
			setAttr("columnList", columnList);
			renderJson(new String[]{Constant.RESULT,Constant.MESSAGE,"columnList"});
		}catch (Exception e){
			e.printStackTrace();
			renderError("数据执行错误！");
		}
	}
	
	
	@SuppressWarnings("unchecked")
	@UserMethod("DevelopAutocode")
	public void addEditModel(){
		Integer id = getParaToInt("id",0);
		AutocodeModel autocodeModel = new AutocodeModel();
		JSONArray columnList = new JSONArray();
		if(id>0){
			autocodeModel = AutocodeModel.dao.findById(id);
			if(autocodeModel.get("columnList")!=null&&!autocodeModel.getStr("columnList").equals("")){
				columnList = JSON.parseArray(autocodeModel.getStr("columnList"));
			}
		}else {
			autocodeModel.set("component_id", getParaToInt("component_id",0));
			autocodeModel.set("tablename","jsub_");
			//增加默认数据
			JSONObject sort = new JSONObject();
			sort.put("name", "排序");
			sort.put("column", "sort");
			sort.put("inputType", "digits");
			sort.put("default", "100");
			columnList.add(sort);
			JSONObject enable_flag = new JSONObject();
			enable_flag.put("name", "状态");
			enable_flag.put("column", "enable_flag");
			enable_flag.put("inputType", "radio");
			enable_flag.put("change", "ENABLE_FLAG");
			enable_flag.put("search", "eq");
			enable_flag.put("default", "T");
			columnList.add(enable_flag);
		}
		AutocodeComponent autocodeComponent =  AutocodeComponent.dao.findById(autocodeModel.getInt("component_id"));
		AutocodePlugin autocodePlugin = AutocodePlugin.dao.findById(autocodeComponent.getInt("plugin_id"));
		
		setAttr("autocodeComponent",autocodeComponent);
		setAttr("autocodeModel", autocodeModel);
		setAttr("columnList", columnList);
		setAttr("modelList", autocodeService.getModelList(autocodeModel.getInt("component_id")));
		
		Cache cache = Redis.use();
		Map<String,JSONObject> basedata = cache.hgetAll(Constant.R_BASEDATA);
		List<String> basedataList = new ArrayList<String>();
		for(String key:basedata.keySet()){
			if(key.startsWith(autocodePlugin.getStr("code").toUpperCase()+"_")){
				basedataList.add(key);
			}
		}
		basedataList.add("SHIFOU");
		basedataList.add("ENABLE_FLAG");
		basedataList.add("SUCCESSERROR");
		setAttr("basedataList", basedataList);
		render("addEditModel.html");
	}
	@UserMethod("DevelopAutocode")
	public void saveModel(){
		AutocodeModel autocodeModel = getModel(AutocodeModel.class);
		
		List<Record> columnList = new ArrayList<Record>();
		String[] columnNameArr = getParaValues("columnName");
		String[] columnColumnArr = getParaValues("columnColumn");
		String[] inputTypeArr = getParaValues("inputType");
		String[] changeArr = getParaValues("change");
		String[] searchArr = getParaValues("search");
		String[] repeatArr = getParaValues("repeat");
		String[] requiredArr = getParaValues("required");
		String[] defaultArr = getParaValues("default");
		if(columnNameArr!=null){
			for(int m=1;m<=columnNameArr.length;m++){
				if(columnNameArr[m-1].equals("")){
					continue;
				}
				Record columnRecord = new Record();
				columnRecord.set("name", columnNameArr[m-1]);
				if(columnColumnArr[m-1].equals("")){
					renderError("字段名称不能为空");
					return;
				}
				columnRecord.set("column", columnColumnArr[m-1]);
				columnRecord.set("inputType", inputTypeArr[m-1]);
				if(!changeArr[m-1].equals("")){
					columnRecord.set("change", changeArr[m-1]);
				}
				if(!searchArr[m-1].equals("")){
					columnRecord.set("search", searchArr[m-1]);
				}
				if(!repeatArr[m-1].equals("")){
					columnRecord.set("repeat", repeatArr[m-1]);
				}
				columnRecord.set("required", requiredArr[m-1]);
				columnRecord.set("default", defaultArr[m-1]);
				columnList.add(columnRecord);
			}
		}
		if(columnList.size()==0){
			renderError("请维护列");
			return;
		}
		autocodeModel.set("columnList", JsonKit.toJson(columnList));
		if(autocodeModel.get("id")!=null&&autocodeModel.getInt("id")>0){
			autocodeModel.update();
		}else {
			autocodeModel.save();
		}
		setAttr("result", "success");
		setAttr("message", "保存成功！");
		setAttr("id", autocodeModel.getInt("id"));
		renderJson(new String[]{"result","message","id"});
	}
	/*************
	 *Model列表
	**************/
	@UserMethod("DevelopAutocode")
	public void modelList(){
		if(!getPara("is_ajax","F").equals("T")){
			keepPara();
			render("modelList.html");
			return;
		}
		renderPageJson(autocodeService.getModelPage(client, getParaMap()));
	}

	/*************
	 *批量删除Model
	**************/
	@UserMethod("DevelopAutocode")
	public void batchDeleteModel(){
		String[] btSelectItem = getParaValues("btSelectItem");
		autocodeService.batchDelete(AutocodeModel.tablename, btSelectItem);
		renderSuccess();
	}
	
	@UserMethod("DevelopAutocode")
	public void makeCode(){
		Integer id = getParaToInt("id",0);
		AutocodeModel autocodeModel = AutocodeModel.dao.findById(id);
		if(autocodeModel.get("child_model")!=null&&autocodeModel.getInt("child_model")>0){
			AutocodeModel child = AutocodeModel.dao.findById(autocodeModel.getInt("child_model"));
			setAttr("child", child);
		}
		if(autocodeModel.get("parent_model")!=null&&autocodeModel.getInt("parent_model")>0){
			AutocodeModel parent = AutocodeModel.dao.findById(autocodeModel.getInt("parent_model"));
			setAttr("parent", parent);
		}
		AutocodeComponent autocodeComponent = AutocodeComponent.dao.findById(autocodeModel.getInt("component_id"));
		AutocodePlugin autocodePlugin = AutocodePlugin.dao.findById(autocodeComponent.getInt("plugin_id"));

		JSONArray columnList = JSON.parseArray(autocodeModel.getStr("columnList"));
		for(int i=0;i<columnList.size();i++){
			if(columnList.getJSONObject(i).get("repeat")!=null&&!columnList.getJSONObject(i).getString("repeat").equals("")){
				autocodeModel.put("repeat", true);
			}
			if(columnList.getJSONObject(i).get("search")!=null&&!columnList.getJSONObject(i).getString("search").equals("")){
				autocodeModel.put("search", true);
			}
			if(columnList.getJSONObject(i).get("change")!=null&&!columnList.getJSONObject(i).getString("change").equals("")){
				autocodeModel.put("change", true);
			}
			if(columnList.getJSONObject(i).get("inputType")!=null&&columnList.getJSONObject(i).get("inputType").equals("xheditor")){
				autocodeModel.put("xheditor", true);
				autocodeModel.put("full", true);
			}
			if(columnList.getJSONObject(i).get("inputType")!=null&&columnList.getJSONObject(i).get("inputType").equals("datetime")){
				autocodeModel.put("datetime", columnList.getJSONObject(i).getString("column"));
			}
			if(columnList.getJSONObject(i).get("inputType")!=null&&columnList.getJSONObject(i).getString("inputType").indexOf("select2")>-1){
				autocodeModel.put("select2", true);
			}
			if(columnList.getJSONObject(i).get("inputType")!=null&&",select2c,select2d,".indexOf(","+columnList.getJSONObject(i).getString("inputType")+",")>-1){
				autocodeModel.put("select2user", columnList.getJSONObject(i).getString("column"));
			}
		}
		setAttr("height", (columnList.size()+2)*50+50);
		setAttr("autocodeModel", autocodeModel);
		setAttr("model", autocodeModel.getStr("code"));
		setAttr("autocodeComponent", autocodeComponent);
		setAttr("component", autocodeComponent.getStr("code"));
		setAttr("autocodePlugin", autocodePlugin);
		setAttr("plugin", autocodePlugin.getStr("code"));
		setAttr("columnList", columnList);
		
		setAttr("class", autocodeComponent.getStr("code")+autocodeModel.getStr("code"));
		setAttr("object", StringUtil.firstLowerCase(autocodeComponent.getStr("code"))+autocodeModel.getStr("code"));
		render("makeCode.html");
	}
	
	/*************
	 *修改Plugin
	**************/
	@UserMethod("DevelopAutocode")
	public void addEditPlugin(){
		Integer id = getParaToInt("id",0);
		AutocodePlugin autocodePlugin = new AutocodePlugin();
		if(id>0){
			autocodePlugin = AutocodePlugin.dao.findById(id);
		}
		setAttr("autocodePlugin",autocodePlugin);
		render("addEditPlugin.html");
	}

	/*************
	 *保存Plugin
	**************/
	@UserMethod("DevelopAutocode")
	public void savePlugin(){
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		AutocodePlugin autocodePlugin = getModel(AutocodePlugin.class);
		Ret ret = autocodeService.checkRepeat(autocodePlugin,AutocodePlugin.tablename
			,new String[]{"name","名称不能重复！"}
			,new String[]{"code","代码不能重复"});
		if(ret.get(Constant.RESULT).equals(Constant.ERROR)){
			renderRet(ret);
			return;
		}
		saveModel(autocodePlugin,authSession.getId());
		renderSuccess();
	}

	/*************
	 *Plugin列表
	**************/
	@UserMethod("DevelopAutocode")
	public void pluginList(){
		if(!getPara("is_ajax","F").equals("T")){
			render("pluginList.html");
			return;
		}
		renderPageJson(autocodeService.getPluginPage(client, getParaMap()));
	}

	/*************
	 *批量删除Plugin
	**************/
	@UserMethod("DevelopAutocode")
	public void batchDeletePlugin(){
		String[] btSelectItem = getParaValues("btSelectItem");
		if(Db.queryLong("select count(id) from "+AutocodeComponent.tablename+" where Plugin_id in ("+StringUtil.idsToString(btSelectItem)+")")>0){
			renderError("存在子数据，删除失败！");
			return;
		}
		autocodeService.batchDelete(AutocodePlugin.tablename, btSelectItem);
		renderSuccess();
	}
	
	/*************
	 *修改Component
	**************/
	@UserMethod("DevelopAutocode")
	public void addEditComponent(){
		Integer id = getParaToInt("id",0);
		AutocodeComponent autocodeComponent = new AutocodeComponent();
		if(id>0){
			autocodeComponent = AutocodeComponent.dao.findById(id);
		}else{
			autocodeComponent.set("plugin_id",getParaToInt("plugin_id",0));
		}
		setAttr("autocodeComponent",autocodeComponent);
		render("addEditComponent.html");
	}

	/*************
	 *保存Component
	**************/
	@UserMethod("DevelopAutocode")
	public void saveComponent(){
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		AutocodeComponent autocodeComponent = getModel(AutocodeComponent.class);
		Ret ret = autocodeService.checkRepeat(autocodeComponent,AutocodeComponent.tablename
			," and plugin_id="+autocodeComponent.getInt("plugin_id")
			,new String[]{"name","名称不能重复！"}
			,new String[]{"code","代码不能重复！"});
		if(ret.get(Constant.RESULT).equals(Constant.ERROR)){
			renderRet(ret);
			return;
		}
		saveModel(autocodeComponent,authSession.getId());
		renderSuccess();
	}

	/*************
	 *Component列表
	**************/
	@UserMethod("DevelopAutocode")
	public void componentList(){
		if(!getPara("is_ajax","F").equals("T")){
			keepPara();
			render("componentList.html");
			return;
		}
		renderPageJson(autocodeService.getComponentPage(client, getParaMap()));
	}

	/*************
	 *批量删除Component
	**************/
	@UserMethod("DevelopAutocode")
	public void batchDeleteComponent(){
		String[] btSelectItem = getParaValues("btSelectItem");
		if(Db.queryLong("select count(id) from "+AutocodeModel.tablename+" where Component_id in ("+StringUtil.idsToString(btSelectItem)+")")>0){
			renderError("存在子数据，删除失败！");
			return;
		}
		autocodeService.batchDelete(AutocodeComponent.tablename, btSelectItem);
		renderSuccess();
	}
	       		
}
